part of 'index.dart';

class CommentNotificationPage extends StatefulWidget {
  const CommentNotificationPage(this.conversation, {super.key});
  final EMConversation conversation;

  @override
  State<CommentNotificationPage> createState() =>
      _CommentNotificationPageState();
}

class _CommentNotificationPageState extends State<CommentNotificationPage> {
  final refreshController = EasyRefreshController(
    controlFinishRefresh: true,
    controlFinishLoad: true,
  );
  List<EMMessage> messageList = [];

  final int _limit = 20;
  bool _noMore = false;
  String? startMsgId;

  @override
  void initState() {
    super.initState();
    _getMessageList();
  }

  Future<void> _getMessageList({String? start}) async {
    final conversationId = widget.conversation.id;
    final result = await ImManager.of.loadLocalHistoryMessage(
      conversationId,
      startMsgId: start ?? startMsgId,
      limit: _limit,
    );
    messageList.addAll(result);
    messageList.sort((a, b) => b.serverTime.compareTo(a.serverTime));
    if (messageList.isNotEmpty) startMsgId = messageList.first.msgId;
    if (result.length < _limit) _noMore = true;
    setState(() {});
  }

  void onLoading() async {
    if (_noMore) {
      refreshController.finishLoad(IndicatorResult.noMore);
      return;
    }
    try {
      await _getMessageList();
      refreshController.finishLoad();
    } catch (error) {
      refreshController.finishLoad(IndicatorResult.fail);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: const Color(0xFFDCD4FF),
        centerTitle: true,
        title: Text(
          T.current.c_comment_message,
          style: const TextStyle(fontSize: 22, fontWeight: FontWeight.w500),
        ),
      ),
      backgroundColor: const Color(0xFFFAFAFA),
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 12),
        child: CustomPullScrollView(
          controller: refreshController,
          onLoading: onLoading,
          refreshOnStart: false,
          builder: (context, physics) => CustomScrollView(
            physics: physics,
            slivers: [
              if (messageList.isEmpty)
                Padding(
                  padding: const EdgeInsets.only(top: 100),
                  child: Image.asset(
                    Images.bgNoticeEmpty,
                    width: 150,
                    height: 150,
                  ),
                ).sliver,
              SliverList.separated(
                itemBuilder: (context, index) {
                  return _Card(messageList[index]);
                },
                separatorBuilder: (context, index) => Divider(
                  height: 0,
                  thickness: 0.5,
                  color: const Color(0xFFD8D8D8).withOpacity(0.5),
                ),
                itemCount: messageList.length,
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _Card extends StatelessWidget {
  const _Card(this.model);
  final EMMessage model;

  @override
  Widget build(BuildContext context) {
    final attributes = model.attributes ?? {};
    final createTime = attributes['createTime'];
    //final userId = attributes['userId'] as int?;
    final nickname = attributes['fromUserNickname'] as String?;
    final avatar = attributes['fromUserHeadPortraitsUrl'] as String?;
    final imgUrl = attributes['imgUrl'] as String?;
    final id = int.tryParse('${attributes['dynamicId']}');
    final type = int.tryParse('${attributes['dynamicType']}');

    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 12),
      child: Row(
        children: [
          Padding(
            padding: EdgeInsets.only(
              left: Tools.isAr ? 0 : 10,
              right: Tools.isAr ? 0 : 10,
            ),
            child: image(avatar ?? Constants.avatar, width: 40).clipRRect(99),
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(nickname ?? ''),
              Row(
                children: [
                  SizedBox(
                    width: 100,
                    child: Text(
                      T.current.c_replied_to_you,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: const TextStyle(
                        color: Color(0xFF4C85FF),
                        fontSize: 12,
                      ),
                    ),
                  ),
                  const Padding(
                    padding: EdgeInsets.only(top: 3),
                    child: Icon(
                      Icons.chevron_right,
                      size: 12,
                      color: Color(0xFF4C85FF),
                    ),
                  )
                ],
              )
            ],
          ).expanded,
          Text(
            Tools.dateFromS(createTime, 'MM-dd HH:mm'),
            style: const TextStyle(color: Color(0xFFC4C4C4), fontSize: 11),
          ),
          if (imgUrl != null)
            Padding(
              padding: EdgeInsets.only(
                left: Tools.isAr ? 0 : 10,
                right: Tools.isAr ? 10 : 0,
              ),
              child: image(
                imgUrl,
                width: 55,
                height: 55,
                fit: BoxFit.fitWidth,
              ).clipRRect(6),
            ),
        ],
      ),
    ).onTap(() async {
      if (id == null || type == null) return;
      final entity = await ImAPI.getMomentEntity(id.toString());
      if (entity == null) return;
      if (type == 1) {
        Get.to(() => PostDetailPage(), arguments: {"moment": entity});
        return;
      }
      if (type == 2) {
        Get.to(() => PlayerPage(), arguments: {"moment": entity});
        return;
      }
    });
    ;
  }
}
